package dd.lo.chapter10;

import dd.lo.util.ImageUtils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 代码样例基于Example 10-2. Alternative method to combine and threshold image planes
 */
public class Example2 extends Application {

    private enum Mode {
        TRUNC,
        OTSU,
        ;
    }

    private static final int DEFAULT_WIDTH = 1080;
    private static final int DEFAULT_HEIGHT = 768;

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        launch(args);
    }

    private ImageView imageView;

    private Mat srcImg;

    private Mode mode = Mode.TRUNC;

    @Override
    public void start(Stage stage) {
        Button imageChooser = new Button("选择图片");
        imageChooser.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("请选择图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Downloads")
            );
            fileChooser.getExtensionFilters().addAll(
//                    new FileChooser.ExtensionFilter("All Images", "*.*"),
                    new FileChooser.ExtensionFilter("JPEG", "*.jpeg"),
                    new FileChooser.ExtensionFilter("WEBP", "*.webp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png"),
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp")
            );
            File imgFile = fileChooser.showOpenDialog(stage);
            if (null == imgFile) {
                System.out.println("用户取消选中文件");
                return;
            }
            //读取一张图片
            srcImg = Imgcodecs.imread(imgFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);
            if (srcImg.empty()) {
                throw new RuntimeException("图片读取失败");
            }
            thresholdTruncate(srcImg);
        });
        Text modeText = new Text("当前模式：" + mode);
        Button changeModeButton = new Button("切换模式");
        changeModeButton.setOnMouseClicked(e -> {
            if (mode == Mode.TRUNC) {
                mode = Mode.OTSU;
            } else {
                mode = Mode.TRUNC;
            }
            modeText.setText("当前模式：" + mode);
            thresholdTruncate(srcImg);
        });
        FlowPane bottomControl = new FlowPane();
        bottomControl.getChildren().addAll(imageChooser, modeText, changeModeButton);
        bottomControl.setPrefHeight(50);
        BorderPane root = new BorderPane();
        imageView = new ImageView();
        root.setCenter(imageView);
        root.setBottom(bottomControl);
        Scene scene = new Scene(root, DEFAULT_WIDTH, DEFAULT_HEIGHT + 50);
        stage.setScene(scene);
        stage.setTitle("Example2-Alternative way to sum channels and threshold truncate");
        stage.setResizable(false);
        stage.show();
    }

    private void thresholdTruncate(Mat srcImg) {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() {
                Mat dst = new Mat();
                //Split image onto the color planes.
                List<Mat> planes = new ArrayList<>(3);
                Core.split(srcImg, planes);
                Mat b = planes.get(0), g = planes.get(1), r = planes.get(2), s = Mat.zeros(b.size(), CvType.CV_32F);
                //Accumulate separate planes, combine and threshold.
                Imgproc.accumulate(b, s);
                Imgproc.accumulate(g, s);
                Imgproc.accumulate(r, s);
                //Truncate values above 100.
                if (mode == Mode.TRUNC) {
                    s.convertTo(s, CvType.CV_8U);
                    Imgproc.threshold(s, s, 100, 100, Imgproc.THRESH_OTSU);
                } else {
                    Imgproc.threshold(s, s, 100, 100, Imgproc.THRESH_TRUNC);
                }
                s.convertTo(dst, b.type());
                //调整图片大小以用于展示
                ImageUtils.fitImgSize(dst, DEFAULT_WIDTH, DEFAULT_HEIGHT);
                MatOfByte buffer = new MatOfByte();
                Imgcodecs.imencode(".jpeg", dst, buffer);
                Platform.runLater(() -> imageView.setImage(new Image(new ByteArrayInputStream(buffer.toArray()))));
                return null;
            }
        };
        new Thread(task).start();
    }
}
